import React, { useEffect, useState } from 'react';
import {
  Modal,
  Form,
  Input,
  Select,
  Descriptions,
  Row,
  Col,
  Button,
  Timeline,
  Popover,
  message,
} from 'antd';
import { FormInstance } from 'antd/es/form';
import { SignatureItem, CallSignatureItem, OrganizationItem } from 'admin/schema/Cas';
import { filter, find, findIndex, get, map } from 'lodash';
import { getAuditUserByType, getSignatureAuditLogs } from 'admin/servers/servers';
import { CheckCircleOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { getTimelineItemProps } from './TemplateAuditModal';

interface Props {
  title: string;
  visible: boolean;
  onOk: () => void;
  onCancel: () => void;
  form: FormInstance;
  organizations: Omit<OrganizationItem, 'children' | 'description'>[];
  signature: SignatureItem | CallSignatureItem | null;
  type: 'sms' | 'call';
  hasAuditPermission?: boolean;
}

interface AuditUser {
  stepName: string;
  auditUserList: {
    userId: string;
    userName: string;
    nickName: string;
  }[];
}

interface AuditLog {
  id: string;
  auditedAt: number;
  auditedBy: string;
  status: string;
  remark: string;
  templateId: string;
  createdAt: number;
  taskName: string;
  userInfo: {
    id: string;
    username: string;
    nickname: string;
    phone: string;
    email: string;
    status: number;
    face: string;
    createdTime: number;
  };
}

const SignatureAuditModal: React.FC<Props> = ({
  title,
  visible,
  onOk,
  onCancel,
  form,
  organizations,
  signature,
  type,
  hasAuditPermission,
}) => {
  const [auditUsers, setAuditUsers] = useState<AuditUser[]>([]);
  const [auditLogs, setAuditLogs] = useState<AuditLog[]>([]);

  const renderFileDownload = (fileUrl: string | undefined) => {
    if (!fileUrl) return '-';
    const urls = JSON.parse(fileUrl);
    if (!Array.isArray(urls) || urls.length === 0) return '-';
    return map(urls, (url: any, index: number) => {
      const regex = /\.(jpe?g|png|gif|webp|bmp|svg|pdf)(\?|$)/i;
      if (regex.test(url.path)) {
        return (
          <a key={index} href={url.path} target="_blank" rel="noopener noreferrer">
            {url.realName}
          </a>
        );
      }
      return (
        <a
          key={index}
          href={url.path}
          download={url.realName}
          target="_blank"
          rel="noopener noreferrer"
        >
          {url.realName}
        </a>
      );
    });
  };

  const fetchAuditUsers = async () => {
    try {
      const response = await getAuditUserByType('SIGN');
      if (response.status === 200) {
        setAuditUsers([
          { stepName: '提交', auditUserList: [] },
          ...response.data.stepAuditUsers,
          { stepName: '结束', auditUserList: [] },
        ]);
      }
    } catch (error) {
      console.error('获取审批流程出错:', error);
    }
  };

  // 获取审核日志
  const fetchAuditLogs = async () => {
    if (!signature?.id) return;
    try {
      const response = await getSignatureAuditLogs(signature.id);
      if (response.status === 200) {
        setAuditLogs(response.data);
      }
    } catch (error) {
      console.error('获取审核日志出错:', error);
      message.error('获取审核日志失败');
    }
  };

  useEffect(() => {
    if (visible) {
      fetchAuditUsers();
      fetchAuditLogs();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible, signature?.id]);

  const getStatusText = (status: string) => {
    switch (status) {
      case 'PENDING':
        return '待审核';
      case 'UNDER_REVIEW':
        return '审核中';
      case 'APPROVED':
        return '审核通过';
      case 'REJECTED':
        return '审核驳回';
      default:
        return status;
    }
  };

  return (
    <Modal
      title={title}
      visible={visible}
      onOk={onOk}
      onCancel={onCancel}
      destroyOnClose
      width={1200}
      style={{ top: 20 }}
      maskClosable={false}
      okButtonProps={{
        style: {
          display: hasAuditPermission ? 'inline' : 'none',
        },
      }}
    >
      <Row gutter={24}>
        <Col span={12}>
          <div style={{ marginBottom: 24 }}>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
              <h3>签名信息</h3>
            </div>

            {type === 'sms' ? (
              // 短信签名详情
              <Descriptions column={2}>
                <Descriptions.Item label="签名名称">
                  {(signature as SignatureItem)?.name}
                </Descriptions.Item>
                <Descriptions.Item label="类型">
                  {(signature as SignatureItem)?.type}
                </Descriptions.Item>
                <Descriptions.Item label="单位名称">
                  {find(organizations, { id: (signature as SignatureItem)?.organizationId })?.name}
                </Descriptions.Item>
                <Descriptions.Item label="联系电话">
                  {(signature as SignatureItem)?.phone}
                </Descriptions.Item>
                <Descriptions.Item label="签名描述">
                  {(signature as SignatureItem)?.description || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="创建时间">
                  {signature?.createdAt ? new Date(signature.createdAt).toLocaleString() : '-'}
                </Descriptions.Item>
                <Descriptions.Item label="状态">
                  {getStatusText(signature?.status || '')}
                </Descriptions.Item>
              </Descriptions>
            ) : (
              // 智能外呼签名详情
              <Descriptions column={2}>
                <Descriptions.Item label="签名名称">
                  {(signature as CallSignatureItem)?.name}
                </Descriptions.Item>
                <Descriptions.Item label="单位名称">
                  {
                    find(organizations, { id: (signature as CallSignatureItem)?.organization })
                      ?.name
                  }
                </Descriptions.Item>
                <Descriptions.Item label="并发数">
                  {(signature as CallSignatureItem)?.concurrency}
                </Descriptions.Item>
                <Descriptions.Item label="创建时间">
                  {signature?.createdAt ? new Date(signature.createdAt).toLocaleString() : '-'}
                </Descriptions.Item>
                <Descriptions.Item label="状态">
                  {getStatusText(signature?.status || '')}
                </Descriptions.Item>
              </Descriptions>
            )}
          </div>
          {type === 'sms' && (
            <div>
              <h3>证件信息</h3>
              <Descriptions column={1}>
                <Descriptions.Item contentStyle={{ flexDirection: 'column' }} label="身份证正面">
                  {renderFileDownload((signature as SignatureItem)?.idCardFrontImagePath)}
                </Descriptions.Item>
                <Descriptions.Item contentStyle={{ flexDirection: 'column' }} label="身份证反面">
                  {renderFileDownload((signature as SignatureItem)?.idCardBackImagePath)}
                </Descriptions.Item>
                <Descriptions.Item
                  contentStyle={{ flexDirection: 'column' }}
                  label="统一社会信用代码证"
                >
                  {renderFileDownload((signature as SignatureItem)?.certificatePath)}
                </Descriptions.Item>
                <Descriptions.Item
                  contentStyle={{ flexDirection: 'column' }}
                  label="法人或授权委托人免冠证件照电子版"
                >
                  {renderFileDownload((signature as SignatureItem)?.powerOfLetter)}
                </Descriptions.Item>
                <Descriptions.Item contentStyle={{ flexDirection: 'column' }} label="授权书">
                  {renderFileDownload((signature as SignatureItem)?.powerOfAttorney)}
                </Descriptions.Item>
              </Descriptions>
            </div>
          )}

          {type === 'call' && (
            <div>
              <h3>文件信息</h3>
              <Descriptions column={1}>
                <Descriptions.Item contentStyle={{ flexDirection: 'column' }} label="话术场景">
                  {renderFileDownload((signature as CallSignatureItem)?.scriptScenario)}
                </Descriptions.Item>
                <Descriptions.Item contentStyle={{ flexDirection: 'column' }} label="安全承诺书">
                  {renderFileDownload((signature as CallSignatureItem)?.securityCommitment)}
                </Descriptions.Item>
              </Descriptions>
            </div>
          )}
        </Col>

        <Col span={12} style={{ borderLeft: '1px solid #f0f0f0' }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16 }}>
              <h3 style={{ margin: 0, marginRight: 8 }}>审核日志</h3>
              <Popover
                title="审批流程"
                content={
                  <Timeline mode="alternate" style={{ width: 300 }}>
                    {map(auditUsers, (step, index) => {
                      const currentStatus = get(auditLogs, '[0].status');
                      const currentStepIndex = findIndex(auditUsers, {
                        stepName: auditLogs[0]?.taskName,
                      });
                      const content = (
                        <div>
                          <div style={{ fontWeight: 'bold' }}>{step.stepName}</div>
                          <div style={{ fontSize: '12px', color: '#666' }}>
                            {map(
                              filter(step.auditUserList, item => item.userName !== 'admin'),
                              user => (
                                <span key={user.userId} style={{ marginRight: 8 }}>
                                  {user.nickName || user.userName}
                                </span>
                              )
                            )}
                          </div>
                        </div>
                      );
                      return (
                        <Timeline.Item
                          {...getTimelineItemProps(index, currentStatus, currentStepIndex)}
                        >
                          {content}
                        </Timeline.Item>
                      );
                    })}
                  </Timeline>
                }
                trigger="hover"
              >
                <Button type="link" style={{ padding: 0, height: 'auto' }}>
                  审批流程
                </Button>
              </Popover>
            </div>
            <Timeline>
              {map(auditLogs, log => (
                <Timeline.Item key={log.id}>
                  <p>
                    {log?.userInfo?.nickname || log?.userInfo?.username || log.auditedBy} 于{' '}
                    {new Date(log.auditedAt).toLocaleString()} 完成 {log.taskName}
                  </p>
                  {log.remark && <p>备注：{log.remark}</p>}
                </Timeline.Item>
              )).reverse()}
              {['PENDING', 'REJECTED', 'UNDER_REVIEW'].includes(get(auditLogs, '[0].status')) && (
                <Timeline.Item
                  dot={<ClockCircleOutlined className="timeline-clock-icon" />}
                  color="red"
                >
                  {get(auditLogs, '[0].status') === 'PENDING' && (
                    <>
                      等待 {get(auditUsers, '[1].stepName')} （审批人：
                      {map(
                        filter(
                          get(auditUsers, '[1].auditUserList'),
                          item => item.userName !== 'admin'
                        ),
                        item => item.nickName || item.userName
                      ).join(', ')}
                      ）
                    </>
                  )}
                  {get(auditLogs, '[0].status') === 'UNDER_REVIEW' && (
                    <>
                      等待{' '}
                      {get(auditUsers, [
                        findIndex(auditUsers, { stepName: auditLogs[0]?.taskName }) + 1,
                        'stepName',
                      ])}{' '}
                      （审批人：
                      {map(
                        filter(
                          get(auditUsers, [
                            findIndex(auditUsers, { stepName: auditLogs[0]?.taskName }) + 1,
                            'auditUserList',
                          ]),
                          item => item.userName !== 'admin'
                        ),
                        item => item.nickName || item.userName
                      ).join(', ')}
                      ）
                    </>
                  )}
                  {get(auditLogs, '[0].status') === 'REJECTED' && '等待 再次提交'}
                </Timeline.Item>
              )}
              {get(auditLogs, '[0].status') === 'APPROVED' && (
                <Timeline.Item
                  dot={<CheckCircleOutlined className="timeline-clock-icon" />}
                  color="green"
                >
                  审核通过
                </Timeline.Item>
              )}
            </Timeline>
            <p style={{ fontWeight: 700 }}>
              注意：签名申请运营商审核预计需要7-10个工作日，已报备过短信签名的身份证信息不可再次报备
            </p>
          </div>
          {hasAuditPermission && (
            <div>
              <h3>审核表单</h3>
              <Form form={form} layout="vertical">
                <Form.Item
                  name="auditStatus"
                  label="审核结果"
                  rules={[{ required: true, message: '请选择审核结果' }]}
                >
                  <Select placeholder="请选择审核结果">
                    <Select.Option value="APPROVED">通过</Select.Option>
                    <Select.Option value="REJECTED">驳回</Select.Option>
                  </Select>
                </Form.Item>

                <Form.Item
                  name="remark"
                  label="审核备注"
                  rules={[
                    { required: true, message: '请输入审核备注' },
                    { max: 255, message: '请输入255位以内字符' },
                  ]}
                >
                  <Input.TextArea rows={4} placeholder="请输入审核备注" />
                </Form.Item>
              </Form>
            </div>
          )}
        </Col>
      </Row>
    </Modal>
  );
};

// 使用 React.memo 优化组件性能，避免不必要的重渲染
export default React.memo(SignatureAuditModal);
